package com.fms.sys.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fms.common.utils.SecurityUtils;
import com.fms.sys.entity.Schedule;
import com.fms.sys.mapper.ScheduleMapper;
import com.fms.sys.service.IScheduleService;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.web.client.RestTemplate;
import java.time.LocalDateTime;
import java.util.List;

@Service
public class ScheduleServiceImpl extends ServiceImpl<ScheduleMapper, Schedule> implements IScheduleService {

    // Server酱SendKey（请替换为你的真实SendKey）
    private static final String SERVER_CHAN_KEY = "SCT278343TYZSUB35G7JHg0lmuZ1FcWjvA";

    @Override
    public Page<Schedule> getScheduleList(Page<Schedule> page, String title) {
        LambdaQueryWrapper<Schedule> wrapper = new LambdaQueryWrapper<>();
        if (StringUtils.hasText(title)) {
            wrapper.like(Schedule::getTitle, title);
        }
        wrapper.orderByDesc(Schedule::getCreateTime);
        return this.page(page, wrapper);
    }

    @Override
    public boolean addSchedule(Schedule schedule) {
        schedule.setCreateBy(SecurityUtils.getCurrentUserId());
        schedule.setIsReminded(0); // 新增日程时默认未提醒
        return this.save(schedule);
    }

    @Override
    public boolean updateSchedule(Schedule schedule) {
        schedule.setUpdateBy(SecurityUtils.getCurrentUserId());
        return this.updateById(schedule);
    }

    @Override
    public boolean deleteSchedule(Long id) {
        return this.removeById(id);
    }

    @Override
    public Schedule getScheduleById(Long id) {
        return this.getById(id);
    }

    /**
     * 每分钟检测未完成且即将结束的日程并推送提醒
     */
    @Scheduled(cron = "0 */1 * * * ?")
    public void sendScheduleReminders() {
        System.out.println("【定时任务】开始检查日程结束提醒：" + LocalDateTime.now());
        int minutesBefore = 10;
        LocalDateTime now = LocalDateTime.now();
        LocalDateTime remindTime = now.plusMinutes(minutesBefore);

        LambdaQueryWrapper<Schedule> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Schedule::getStatus, 0)
                .eq(Schedule::getIsReminded, 0)
                .le(Schedule::getEndTime, remindTime)
                .gt(Schedule::getEndTime, now);

        List<Schedule> dueSchedules = this.list(wrapper);
        System.out.println("【定时任务】本次需提醒的日程数量：" + dueSchedules.size());
        for (Schedule schedule : dueSchedules) {
            System.out.println("【定时任务】准备推送日程：" + schedule.getTitle() + "，结束时间：" + schedule.getEndTime());
            pushToWechat(SERVER_CHAN_KEY, "日程即将结束提醒",
                    "标题：" + schedule.getTitle() +
                            "\n内容：" + schedule.getContent() +
                            "\n开始时间：" + schedule.getStartTime() +
                            "\n结束时间：" + schedule.getEndTime());
            schedule.setIsReminded(1);
            this.updateById(schedule);
        }
    }

    private void pushToWechat(String sendKey, String title, String content) {
        try {
            String url = "https://sctapi.ftqq.com/" + sendKey + ".send?title="
                    + title + "&desp=" + content;
            RestTemplate restTemplate = new RestTemplate();
            String result = restTemplate.getForObject(url, String.class);
            System.out.println("Server酱推送结果：" + result);
        } catch (Exception e) {
            System.err.println("Server酱推送失败：" + e.getMessage());
        }
    }
}
